import { Button, Form, message, Upload } from 'antd';
import {useEffect, useState} from 'react';
import {get} from "../../utils/get";

const EditorUpload = (props) => {
  const [OSSData, setOSSData] = useState();
  const token = localStorage.getItem('TOKEN')
  const { value, onChange }=props;
  const init = async () => {
    try {
      const result = await mockGetOSSData();
      setOSSData(result);
    } catch (error) {
      message.error(error);
    }
  };
  const mockGetOSSData = async (filename,uid)=>{
    const token = localStorage.getItem('TOKEN')
    let data= null;
    const res = await get('/oss/policy',token)
    if(res.data.code===0)
    {
      const {host,policy,signature,accessid,dir,expire}=res.data.data
      data={
        dir,
        expire,
        host,
        accessId:accessid,
        policy,
        signature
      }
    }
    return data;
  }
  useEffect( async () => {
    init();
  }, [props]);

  const handleChange = ({ fileList }) => {
    onChange?.([...fileList]);
  };

  const handleRemove = (file) => {
    const files = (value || []).filter((v) => v.url !== file.url);
    onChange?.(files);
  };

  const checkImg=(file)=>{
    const isJPEG = file.type === 'image/jpeg';
    const isJPG = file.type === 'image/jpg';
    const isPNG = file.type === 'image/png';
    const isBMP = file.type === 'image/bmp';
    const isWEBP = file.type === 'image/webp';
    const isPic = isJPG || isPNG || isBMP || isWEBP||isJPEG;
    if (!isPic) {
        message.error('请上传图片');
        return false;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
        message.error('上传图片必须小于 5MB!');
        return false;
    }
    return true;
}
  const getExtraData = (file) => ({
    key: file.url,
    OSSAccessKeyId: OSSData?.accessId,
    policy: OSSData?.policy,
    Signature: OSSData?.signature,
  });

  const beforeUpload = async (file) => {
    let canUpload = checkImg(file)
    if(!canUpload)  return false;
    const expire = OSSData.expire * 1000;
    if (expire < Date.now()) {
        await init();
    }
    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = Date.now() + suffix;
    file.url = OSSData.dir + filename;
    return file;
  };

  const uploadProps = {
    name: 'file',
    fileList: value,
    action:'http://baiblog.oss-cn-guangzhou.aliyuncs.com',
    maxCount:1,
    listType:"picture-card",
    onChange: handleChange,
    onRemove:handleRemove,
    data: getExtraData,
    beforeUpload,
  };
  return (
      <Form.Item label="头像" name="avatar">
        <Upload {...uploadProps}>
          <Button/>
        </Upload>
      </Form.Item>

  );
};
export default EditorUpload;
